#include "gic.h"
#include "key.h"
#include "uart.h"

#define IRQ_GPIO1_16_32 (67 + 32)

void key_init(void)
{
    volatile unsigned int *pRegKey;
    GPIO_Type *gpio1 = (GPIO_Type *)0x0209c000;
	 
	/* 1、把GPIO1_18设置为GPIO功能 */
	pRegKey = (volatile unsigned int *)(0x020e0000 + 0x8c);
	*pRegKey &= ~(0xf);
	*pRegKey |= (0x5);

	/* 2、把GPIO1_18设置为输入引脚 */
	gpio1->GDIR &= ~(1<<18);

	/* 3、设置中断触发方式:双边沿触发 */
	gpio1->EDGE_SEL |= (1<<18);

	/* 4、为避免发生错误的中断, 先清除IO18中断标志位和GPIO1中断 */
	gpio1->ISR |= (1<<18);
	clear_gic_irq(IRQ_GPIO1_16_32);

	/* 5、使能IO14中断,使能GPIO4中断 */
	gpio1->IMR |= (1<<18);	
	gic_enable_irq(IRQ_GPIO1_16_32);
}

void irq_hander_gpio1_16_32(void)
{
	GPIO_Type *gpio1 = (GPIO_Type *)0x0209c000;
	
	if ((gpio1->ISR & (1<<18)) != 0)
	{
		if (gpio1->DR & (1<<18))
		{
			putstring("KEY released!\r\n");
		}
		else
		{
            putstring("KEY pressed!\r\n");			
		}
		gpio1->ISR |= (1<<18);
	}
}
